package com.ali.sqlSession;

import com.ali.pogo.Configuration;
import com.ali.pogo.MappedStatement;
import com.ali.util.GenericTokenParser;
import com.ali.util.ParameterMapping;
import com.ali.util.ParameterMappingTokenHandler;

import javax.sql.DataSource;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class SimpleExcutor implements Excutor {
    @Override
    public <T> List<T> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        DataSource dataSource = configuration.getSource();
        Connection connection = dataSource.getConnection();
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //解析参数类型
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i + 1, o);
        }
        //将返回结果包装成返回对象返回
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        ArrayList<Object> objects = new ArrayList<>();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object o = resultTypeClass.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String cloumnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(cloumnName);
                try {
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(cloumnName, resultTypeClass);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(o, value);
                } catch (Exception e) {
                    System.out.println("======cloumn name========");
                    System.out.println(cloumnName);
                }
            }
            objects.add(o);
        }

        return (List<T>) objects;
    }

    private Class<?> getClassType(String parameterType) throws Exception {
        if (parameterType != null) {
            Class<?> aClass = Class.forName(parameterType);
            return aClass;
        }
        return null;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的sql  select * from table where name= ?
        String parse = genericTokenParser.parse(sql);
        System.out.println("parse sql " + parse);
        //解析出来的参数列表
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        System.out.println("print parameterMapping " + parameterMappings.toString());
        return new BoundSql(parse, parameterMappings);
    }

    public int update(Configuration configuration, MappedStatement mappedStatement, Object parameter) {
        DataSource source = configuration.getSource();
        try {
            Connection connection = source.getConnection();
            BoundSql boundSql = getBoundSql(mappedStatement.getSql());
            //预加载
            PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
            // 解析参数类型
            String parameterType = mappedStatement.getParameterType();
            Class<?> paramesClassType = getClassType(parameterType);
            List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
            for (int i = 0; i < parameterMappingList.size(); i++) {
                ParameterMapping parameterMapping = parameterMappingList.get(i);
                Field declaredField = paramesClassType.getDeclaredField(parameterMapping.getContent());
                declaredField.setAccessible(true);
                Object o = declaredField.get(parameter);
                preparedStatement.setObject(i + 1, o);
            }

            int i = preparedStatement.executeUpdate();
            return i;


        } catch (Exception e) {

        }

        return 0;
    }

    public int delete(Configuration configuration,MappedStatement mappedStatement,Object parameter){
        DataSource source = configuration.getSource();
        try {
            Connection connection = source.getConnection();
            BoundSql boundSql = getBoundSql(mappedStatement.getSql());
            PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
            preparedStatement.setObject(1,parameter);
            int i = preparedStatement.executeUpdate();
            return i;

        }catch (Exception e){
            int a = 1;
        }
        return 0;
    }
}
